package cn.zyl.common.redis.util;

import cn.zyl.common.redis.exception.MiniRedisException;

import java.io.UnsupportedEncodingException;

/** MiniSafeEncoderTool 工具类说明: 字符串编码工具类
 * @author wsz
 * @date 2020-08-07
 * @version v1.0
 */
public class MiniSafeEncoderTool {
    private MiniSafeEncoderTool(){throw new IllegalAccessError("MiniSafeEncoderTool");}
    private final static String CHARSET = "UTF-8";

    /**
     * 字符串数组 转 字节码二维数组，编码方式utf8
     * @param strS 字符串数组
     * @return 字节码二维数组
     */
    public static byte[][] encodeMany(final String... strS) {
        byte[][] many = new byte[strS.length][];
        for (int i = 0; i < strS.length; i++) {
            many[i] = encode(strS[i]);
        }
        return many;
    }

    /**
     * 字符串 转 字节数组，编码方式utf8
     * @param str 字符串
     * @return 字节数组
     */
    public static byte[] encode(final String str) {
        try {
            MiniRedisException.isNullThrow(str,"value sent to redis cannot be null");
            return str.getBytes(CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new MiniRedisException(e);
        }
    }

    /**
     * 字节数组 转 字符串，编码方式utf8
     * @param data 字节数组
     * @return 字符串
     */
    public static String encode(final byte[] data) {
        try {
            return new String(data, CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new MiniRedisException(e);
        }
    }
}